<template>
  <div class="meeting-room-management-page">
    <h2>会议室管理</h2>
    
    <!-- 搜索和过滤区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="会议室名称">
          <el-input v-model="searchForm.roomname" placeholder="请输入会议室名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="会议室类型">
          <select v-model="searchForm.roomType" class="custom-select">
            <option value="">全部类型</option>
            <option value="1">教室</option>
            <option value="2">圆桌</option>
            <option value="3">董事会</option>
            <option value="4">多媒体</option>
          </select>
        </el-form-item>
        <el-form-item label="容纳人数">
          <el-input-number v-model="searchForm.capacity" :min="0" placeholder="最小容纳人数" clearable></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <select v-model="searchForm.status" class="custom-select">
            <option value="">全部状态</option>
            <option value="0">未使用</option>
            <option value="1">使用中</option>
          </select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 添加会议室按钮 -->
      <el-button type="primary" @click="showAddDialog">添加会议室</el-button>
    </div>

    <!-- 会议室列表 -->
    <el-table 
      :data="meetingRooms" 
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="roomId" label="ID" width="80" />
      <el-table-column prop="roomname" label="会议室名称" width="120" />
      <el-table-column label="类型" width="100">
        <template #default="{ row }">
          {{ getRoomType(row.roomType) }}
        </template>
      </el-table-column>
      <el-table-column prop="capacity" label="容纳人数" width="100" />
      <el-table-column prop="area" label="面积" width="100">
        <template #default="{ row }">
          {{ row.area }}㎡
        </template>
      </el-table-column>
      <el-table-column label="设备状态" width="300">
        <template #default="{ row }">
          <el-tag :type="row.projector === 1 ? 'success' : 'danger'" style="margin-right: 5px">
            投影仪{{ row.projector === 1 ? '正常' : '异常' }}
          </el-tag>
          <el-tag :type="row.sound === 1 ? 'success' : 'danger'" style="margin-right: 5px">
            音响{{ row.sound === 1 ? '正常' : '异常' }}
          </el-tag>
          <el-tag :type="row.internet === 1 ? 'success' : 'danger'">
            网络{{ row.internet === 1 ? '正常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格/小时" width="120">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getRoomStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑会议室对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加会议室' : '编辑会议室'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="roomForm" :rules="rules" ref="roomFormRef" label-width="100px">
        <el-form-item label="会议室名称" prop="roomname">
          <el-input v-model="roomForm.roomname" placeholder="请输入会议室名称" />
        </el-form-item>
        <el-form-item label="会议室类型" prop="roomType">
          <select v-model="roomForm.roomType" class="custom-select">
            <option value="1">教室</option>
            <option value="2">圆桌</option>
            <option value="3">董事会</option>
            <option value="4">多媒体</option>
          </select>
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number v-model="roomForm.capacity" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input-number v-model="roomForm.area" :min="1" :precision="2" :step="1" />
          <span class="unit">㎡</span>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-checkbox v-model="roomForm.projector" :true-value="1" :false-value="0">投影仪正常</el-checkbox>
          <el-checkbox v-model="roomForm.sound" :true-value="1" :false-value="0">音响正常</el-checkbox>
          <el-checkbox v-model="roomForm.internet" :true-value="1" :false-value="0">网络正常</el-checkbox>
        </el-form-item>
        <el-form-item label="价格/小时" prop="price">
          <el-input-number v-model="roomForm.price" :min="0" :precision="2" :step="10" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <select v-model="roomForm.status" class="custom-select">
            <option value="0">未使用</option>
            <option value="1">使用中</option>
          </select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAllRooms, getRoomsByPage, getRoomsByCondition, createRoom, updateRoom, deleteRoom } from '@/apis/room';

// 状态变量
const meetingRooms = ref([]);
const dialogVisible = ref(false);
const dialogType = ref('add');
const roomFormRef = ref(null);
const currentRoom = ref(null);
const loading = ref(false);
const submitting = ref(false);
const error = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  roomname: '',
  roomType: '',
  capacity: '',
  status: ''
});

// 会议室表单
const roomForm = ref({
  roomname: '',
  roomType: '1',
  capacity: 1,
  area: 20,
  projector: 1,
  sound: 1,
  internet: 1,
  price: 0,
  status: '0'
});

// 表单验证规则
const rules = {
 roomname: [
    { required: true, message: '请输入会议室名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roomType: [
    { required: true, message: '请选择会议室类型', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入容纳人数', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入会议室面积', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 获取所有会议室
const fetchMeetingRooms = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    let response;
    const hasSearchCriteria = Object.values(searchForm).some(value => 
      value !== '' && value !== null && value !== undefined
    );
    
    console.log('搜索条件:', searchForm);
    
    if (hasSearchCriteria) {
      // 条件查询
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      };
      
      // 创建符合后端接口要求的查询对象
      const condition = {};
      
      // 只添加非空条件
      if (searchForm.roomname && searchForm.roomname.trim() !== '') {
        condition.roomname = searchForm.roomname;
      }
      
      if (searchForm.roomType !== '') {
        condition.roomType = parseInt(searchForm.roomType, 10);
      }
      
      if (searchForm.capacity && searchForm.capacity > 0) {
        condition.capacity = searchForm.capacity;
      }
      
      if (searchForm.status !== '') {
        condition.status = parseInt(searchForm.status, 10);
      }
      
      console.log('发送到后端的查询条件:', condition);
      
      // 注意：后端接口直接接收Room对象，而不是包装在condition中
      response = await getRoomsByCondition({
        pageNum: params.pageNum,
        pageSize: params.pageSize,
        condition: condition
      });
    } else {
      // 普通分页查询
      response = await getRoomsByPage(currentPage.value, pageSize.value);
    }
    
    console.log('API响应:', response);
    
    if (response.code === 200) {
      meetingRooms.value = response.data.records;
      total.value = response.data.total;
    } else {
      error.value = response.msg || '获取会议室列表失败';
      ElMessage.error(error.value);
    }
  } catch (err) {
    console.error('获取会议室列表出错:', err);
    error.value = '获取会议室列表失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchMeetingRooms();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  fetchMeetingRooms();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  fetchMeetingRooms();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchMeetingRooms();
};

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add';
  roomForm.value = {
    roomname: '',
    roomType: '1',
    capacity: 1,
    area: 20,
    projector: 1,
    sound: 1,
    internet: 1,
    price: 0,
    status: '0'
  };
  dialogVisible.value = true;
};

// 显示编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit';
  currentRoom.value = row;
  roomForm.value = {
    ...row,
    roomType: String(row.roomType),
    status: String(row.status),
    projector: Number(row.projector),
    sound: Number(row.sound),
    internet: Number(row.internet)
  };
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!roomFormRef.value) return;
  
  await roomFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      
      try {
        const formData = {
          ...roomForm.value,
          roomType: parseInt(roomForm.value.roomType, 10),
          status: parseInt(roomForm.value.status, 10),
          projector: Number(roomForm.value.projector),
          sound: Number(roomForm.value.sound),
          internet: Number(roomForm.value.internet)
        };

        let response;
        if (dialogType.value === 'add') {
          response = await createRoom(formData);
        } else {
          response = await updateRoom(currentRoom.value.roomId, formData);
        }

        if (response.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
          dialogVisible.value = false;
          fetchMeetingRooms(); // 重新加载会议室列表
        } else {
          ElMessage.error(response.msg || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error('提交表单出错:', error);
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 获取会议室类型文本
const getRoomType = (type) => {
  const types = {
    1: '教室',
    2: '圆桌',
    3: '董事会',
    4: '多媒体'
  };
  return types[type] || '未知类型';
};

// 获取状态文本
const getRoomStatus = (status) => {
  const statuses = {
    0: '未使用',
    1: '使用中'
  };
  return statuses[status] || '未知状态';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    0: 'success',
    1: 'warning'
  };
  return types[status] || '';
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除会议室"${row.roomname}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await deleteRoom(row.roomId);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        fetchMeetingRooms(); // 重新加载会议室列表
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除会议室出错:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

onMounted(() => {
  fetchMeetingRooms();
});
</script>

<style scoped>
.meeting-room-management-page {
  padding: 1rem;
  width: 100%;
  box-sizing: border-box;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 1rem;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex: 1;
  min-width: 300px;
}

.custom-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  background-color: white;
  height: 42px;
  min-width: 180px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tag) {
  margin: 2px;
}

.unit {
  margin-left: 5px;
  color: #606266;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .filter-container {
    flex-direction: column;
  }

  .search-form {
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .meeting-room-management-page {
    padding: 0.5rem;
  }

  .search-form {
    min-width: 100%;
  }

  :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }

  :deep(.el-form-item__content) {
    width: 100%;
  }

  .custom-select {
    min-width: 100%;
  }

  :deep(.el-table) {
    width: 100%;
    overflow-x: auto;
  }
}

@media screen and (max-width: 480px) {
  .meeting-room-management-page {
    padding: 0.25rem;
  }

  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  :deep(.el-form-item__content) {
    margin-left: 80px !important;
  }
}
</style> 